package com.xmh.ffmpeg;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.*;
import java.util.List;

import static com.xmh.ffmpeg.CmdTest.cmdRunTest;
import static com.xmh.ffmpeg.TakeFilePathAndName.getFileNameListByPath;

/**
 * ffmpeg -f concat -safe 0 -i filelist.txt -c copy output.mp4
 *
 * <p>        filelist.txt  content
 * file 'K:\word_IDEA\ffmpeg\Download\1629642134308.mp4'
 * file 'K:\word_IDEA\ffmpeg\Download\1629642134648.mp4'
 * file 'K:\word_IDEA\ffmpeg\Download\1629642135181.mp4'
 * </p>
 * <p>
 * TakeFilePathAndName.class can get all video file name list, just run the class
 */
@Slf4j
public class DownloadVideo {

    @Test
    public void test1() throws IOException, InterruptedException {
//        String imageUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.hispanicresearchcenter.org%2Fwp-content%2Fuploads%2F2016%2F09%2FInfographic-Hispanic-Boys-Young-Men-11.png&refer=http%3A%2F%2Fwww.hispanicresearchcenter.org&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623555780&t=e9f2c10f395e0c2d3b5e041bdf0fc185";
//        sendHttp(imageUrl);
        String startUrl = "https://www.102i1e21.com/dongman/2020_01/06/dongman_xteu22k7/dongman_xteu22k7";
//        String startUrl = "https://www.102i1e21.com/dongman/2020_01/06/dongman_EaTuqNnv_wm/dongman_EaTuqNnv_wm";
//        String startUrl = "https://www.102i1e21.com/sise/sise_online/dongman_xteu22k7/hls/1/index";
        String endUrl = ".ts";

        String filePath = "K:\\word_IDEA\\ffmpeg\\Download\\";

        for (int i = 0; i < 136; i++) {
            downloadNet(startUrl + i + endUrl, filePath);
        }

        List<String> fileNameListByPath = getFileNameListByPath(filePath, 0);

        StringBuilder stringBuilder = new StringBuilder("ffmpeg -i \"concat:");

        fileNameListByPath.forEach(e -> {
            stringBuilder.append(filePath).append(e).append("|");
        });

        stringBuilder.append("\" -c copy ").append(filePath).append("output.mp4");

        cmdRunTest(stringBuilder.toString());

        Thread.sleep(10000);

        fileNameListByPath.forEach(e -> new File(filePath + e).delete());
//        downImages(filePath, imageUrl);
//        downImages("/Download", "https://e1v-h.phncdn.com/hls/videos/202004/20/305761591/,1080P_4000K,720P_4000K,480P_2000K,240P_400K,_305761591.mp4.urlset/seg-6-f2-v1-a1.ts?validfrom=1620047129&validto=1620054329&ip=38.143.3.108&ipa=38.143.3.108&hdl=-1&hash=nz8U4f7k2VCFzUMA8oU3NLXHCl4%3D");
    }

    public static String tcpPost(String clientIp, int clientPort, String msg) {
        try {
            Socket socket = new Socket(clientIp, clientPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(msg.getBytes("GBK"));
            outputStream.flush();
            socket.shutdownOutput();

            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[512]; //这里最好是1024~8192之间
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                bytesOut.write(buffer, 0, len);
            }
            String respData = bytesOut.toString("GBK");
            System.out.println("返回数据为:" + new String(respData));
            bytesOut.close();
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public void downloadNet(String urlPath, String filePath) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL(urlPath);

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(new File(filePath + System.currentTimeMillis() + ".mp4"));

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据图片的URL下载的图片到本地的filePath
     *
     * @param filePath 文件夹
     * @param imageUrl 图片的网址
     */
    public static void downImages(String filePath, String imageUrl) {
        // 截取图片的名称
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"));

        //创建文件的目录结构
        File files = new File(filePath);
        if (!files.exists()) {// 判断文件夹是否存在，如果不存在就创建一个文件夹
            files.mkdirs();
        }
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream is = connection.getInputStream();
            // 创建文件
            File file = new File(filePath + System.currentTimeMillis() + ".jpg");
            FileOutputStream out = new FileOutputStream(file);
            int i = 0;
            while ((i = is.read()) != -1) {
                out.write(i);
            }
            is.close();
            out.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void ffmpegChange(File file, File fileSave) {
        long startTime = System.currentTimeMillis();
        try {
            log.info("=========文件 " + file + " 正在压缩中");
            Runtime runtime = Runtime.getRuntime();
            String cutCmd = "ffmpeg -i " + file + " -r 15 -b:v 750k  -s 1280*720 " + fileSave;
            Process proce = runtime.exec(cutCmd);
            InputStream erro = proce.getErrorStream();
            byte[] a = new byte[1024];
            int j = 0;
            while ((j = erro.read(a)) > -1) {
//                logger.info(new String(a));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("=========文件 " + file + " 正在转换出现异常");
        }
        log.info("=========文件 " + file + " 压缩完成");
        long endTime = System.currentTimeMillis();
        log.info("压缩完成时间 " + (endTime - startTime) + "ms");
    }

//    public void downloadVideo() {
//        List<LearnVideo> learnVideos = this.list((new QueryWrapper<LearnVideo>())
//                        .eq("fix_status","0")
////            .eq("autoid",787)
//        );
//        for (LearnVideo learnVideo : learnVideos) {
//            // 文件存放目录
//            String filePath = path + relativePath + learnVideo.getWebGuid() + "\\";
//            String fileRelativePath = relativePath + learnVideo.getWebGuid() + "\\";
//            String sourceThumbnail = learnVideo.getLearnVideoSourceThumbnail();
//            String sourceUrl2 = learnVideo.getSourceUrl2();
//            String sourceUrl3 = learnVideo.getSourceUrl3();
//            String otherUrl = StringUtils.isNotEmpty(sourceUrl2) ? sourceUrl2 : sourceUrl3;
//            if (StringUtils.isNotEmpty(otherUrl)) {
//                learnVideo.setLearnVideoSoureUrl(otherUrl);
//            }
//            String learnVideoSoureUrl = learnVideo.getLearnVideoSoureUrl();
//            //下载缩略图 并保存本地相对路径
//            if (StringUtils.isNotEmpty(sourceThumbnail)) {
//                handleNormalThumb(filePath, fileRelativePath, learnVideo, sourceThumbnail);
//            }
//            // 下载媒体文件 并保存相对路径
//            if (StringUtils.isNotEmpty(learnVideoSoureUrl)) {
//                String[] split = learnVideoSoureUrl.split("/");
//                String name = split[split.length - 1];
//                name = String.valueOf(RandomUtil.randomInt(1, 99)) + name;
//                sleepHandle(learnVideo);
//                if (learnVideoSoureUrl.contains("oss")) {
//                    String referer = learnVideo.getLearnVideoWebSourceUrl();
//                    DownloadPictureTest.downloadPictureWithOSS(learnVideoSoureUrl, filePath + "temp\\", name, referer);
//                } else {
//                    DownloadPictureTest.downloadPictureSSL(learnVideoSoureUrl, filePath + "temp\\", name);
//                }
//                learnVideo.setLearnVideoPlayUrl(fileRelativePath + name);
//                //另外起线程压缩视频
//                File file = new File(filePath + "temp\\" + name);
//                File file2 = new File(filePath + name);
//                MyUtil.ffmpegChange(file, file2);
//                //转换完成后删除temp文件
//                file.delete();
//            }
//            learnVideo.setFixStatus("1");
//            this.updateById(learnVideo);
//        }
//    }

    public static Long ffmpegChange2(File file, File fileSave) {
        long startTime = System.currentTimeMillis();
        //获取视频宽高
        File source = file;
        Encoder encoder = new Encoder();
        int width = 1280;
        int height = 720;
        try {
            MultimediaInfo m = encoder.getInfo(source);
            long ls = m.getDuration();
            log.info("此视频时长为:" + ls / 60000 + "分" + (ls) / 1000 + "秒！");
            // 视频帧宽高
            int height1 = m.getVideo().getSize().getHeight();
            log.info("此视频高度为:" + height1);
            int width1 = m.getVideo().getSize().getWidth();
            log.info("此视频宽度为:" + width1);
            log.info("此视频格式为:" + m.getFormat());
            if (height1 > width1) {
                width = width1;
                height = height1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            log.info("=========文件 " + file + " 正在压缩中");
            Runtime runtime = Runtime.getRuntime();
            String cutCmd = "ffmpeg -i " + file + " -r 15 -b:v 750k  -s " + width + "*" + height + " " + fileSave;
            Process proce = runtime.exec(cutCmd);
            InputStream erro = proce.getErrorStream();
            byte[] a = new byte[1024];
            int j = 0;
            while ((j = erro.read(a)) > -1) {
//                logger.info(new String(a));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("=========文件 " + file + " 正在转换出现异常");
        }
        log.info("=========文件 " + file + " 压缩完成");
        long endTime = System.currentTimeMillis();
        log.info("压缩完成时间 " + (endTime - startTime) + "ms");
        return endTime - startTime;
    }

}
